var createError = require('http-errors'); // 访问页面出错时给出友好提示
const path = require('path');
const fs = require('fs');
var express = require('express');
var logger = require('morgan'); // 生成日志
const bodyParser = require('body-parser');
const session = require('express-session'); // session-middleware

const userRouter = require('./routes/users');
const blogRouter = require('./routes/blog');

var app = express();

const logFileName = path.join(__dirname, 'logs', 'access.log');
const writeStream = fs.createWriteStream(logFileName, {
  flags: 'a'
});
app.use(logger('combined', {
  stream: writeStream
}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
  secret: 'wxy613ok', // 看文档，这里的secret最好单独存储，不推荐耦合在代码里
  resave: false,
  saveUninitialized: true,
  cookie: { // 设置cookie过期时间
    maxAge: 30 * 1000
  }
}));
app.use(function(req, res, next) {
  const { session, sessionID } = req
  console.log(session, sessionID)
  next()
});
app.use(bodyParser.urlencoded({ extended: false })); // 解析body
app.use(bodyParser.json()); // 解析body
app.use('/api/blog', blogRouter);
app.use('/api/users', userRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404)); 
});

// error handler
app.use(function(err, req, res, next) {
  console.error(err.message)
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'dev' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json(err);
});

module.exports = app;
